package com.byxy.controller;

import com.byxy.model.Gender;
import com.byxy.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.InvalidIsolationLevelException;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.swing.text.html.HTMLDocument;
import java.io.*;
import java.util.Date;
import java.util.Iterator;

@Controller
public class UserController {
    private static final String[] countries = {"China", "Japan", "North Korea"};

    @RequestMapping("/form.html")
    public ModelAndView user() {
        ModelAndView modelAndView = new ModelAndView("userForm");
        modelAndView.addObject("user", new User());
        modelAndView.addObject("genders", Gender.values());
        modelAndView.addObject("countries", countries);
        return modelAndView;
    }

    @RequestMapping("/result.html")
    public ModelAndView processUser(@ModelAttribute("user") User u) {
        ModelAndView modelAndView = new ModelAndView("userResult");
        modelAndView.addObject("u", u);
        return modelAndView;
    }

    @RequestMapping("/addUser1")
    public String addUser1(String userName, String password) {
        System.out.println("userName is:" + userName);
        System.out.println("password is:" + password);
        return "/user/success";
    }

    @RequestMapping("/addUser2")
    public String addUser2(HttpServletRequest request) {
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        System.out.println("userName is:" + userName);
        System.out.println("password is:" + password);
        return "/user/success";
    }

    @RequestMapping("/addUser3")
    public String addUser3(User user) {
        System.out.println("userName is:" + user.getName());
        System.out.println("password is:" + user.getPassword());
        return "/user/success";
    }

    @RequestMapping("/fileUpload")
    public String fileUpload(@RequestParam("file") CommonsMultipartFile file) throws IOException {
        // 用来检测程序运行时间
        long startTime = System.currentTimeMillis();
        System.out.println("fileName" + file.getOriginalFilename());

        try {
            // 获取输出流
            OutputStream os = new FileOutputStream("E:/" + new Date().getTime() + file.getOriginalFilename());
            // 获取输入流 CommonsMultipartFile 中可以直接得到文件的流
            InputStream is = file.getInputStream();
            int temp;
            while ((temp = is.read()) != (-1)) {
                os.write(temp);
            }
            os.flush();
            os.close();
            os.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("方法一的运行时间: " + String.valueOf(endTime - startTime) + "ms");
        return "/user/success";
    }

    @RequestMapping("/fileUpload2")
    public String fileUpload2(@RequestParam("file") CommonsMultipartFile file) throws IOException {
        long startTime = System.currentTimeMillis();
        System.out.println("fileName: " + file.getOriginalFilename());
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
        String path = "E:/" + new Date().getTime() + file.getOriginalFilename();
//        String path = request.getSession().getServletContext().getRealPath("upload");

        File newFile = new File(path);
        // 通过CommonsMultipartFile的方法直接写文件
        file.transferTo(newFile);
        long endTime = System.currentTimeMillis();
        System.out.println("方法二的运行时间: " + String.valueOf(endTime - startTime) + "ms");
        return "/user/success";
    }

    @RequestMapping("/springUpload")
    public String springUpload(HttpServletRequest request) throws InvalidIsolationLevelException, IOException {
        long startTime = System.currentTimeMillis();
        // 将当前上下文初始化给 CommosMutipartResolver (多部分解析器)
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());

        // 检查form中是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request)) {
            // 将request编程多部分request
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            // 获取multiRequest中所有的文件名
            Iterator iterator = multipartHttpServletRequest.getFileNames();

            while (iterator.hasNext()) {
                // 一次遍历所有文件
                MultipartFile file = multipartHttpServletRequest.getFile(iterator.next().toString());
                if (file != null) {
                    String path = "E:/springUpload" + file.getOriginalFilename();
                    // 上传
                    file.transferTo(new File(path));
                }
            }
        }
        long endTime = System.currentTimeMillis();
        System.out.println("方法三的运行时间: " + String.valueOf(endTime - startTime) + "ms");
        return "/user/success";
    }

    @RequestMapping("/upload")
    public String upload() {
        return "upload";
    }


}
